package com.study.zouchao.superproject.mywellet;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.usb.UsbRequest;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.study.zouchao.superproject.R;
import com.study.zouchao.superproject.base_zou.api_zou.Api_C;
import com.study.zouchao.superproject.login.model.entity.User;
import com.study.zouchao.superproject.login.model.entity.result.LoginResult;
import com.study.zouchao.superproject.logininterceptor.LoginStatusUtil;
import com.study.zouchao.superproject.mywellet.model.chargeresult.ChargeResult;
import com.study.zouchao.superproject.util.App;
import com.study.zouchao.superproject.util.RxSchedulers;
import com.study.zouchao.superproject.util.StringUtils;
import com.study.zouchao.superproject.util.ToastUtils;
import com.study.zouchao.superproject.util.api.api.Api;
import com.study.zouchao.superproject.web.WebActivity;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscription;
import rx.functions.Action1;

public class MyWelletActivity extends AppCompatActivity {

    private Subscription mSupCharge;

    @BindView(R.id.id_ll_my_wellet)
    LinearLayout mLlMyWellet;

    @BindView(R.id.wallet_yue_1)
    TextView mTvYue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_wellet);
        ButterKnife.bind(this);
        initInfos();
    }

    private void initInfos() {
        User userBean = LoginStatusUtil.getLoginDataByBean(this);
        if (userBean==null) return;
        mTvYue.setText(userBean.getBalance()+".00");
    }

    public static void actionMyWelletActivity(Context context) {
        Intent intent = new Intent(context, MyWelletActivity.class);
        context.startActivity(intent);
    }

    @OnClick({R.id.wallet_ofo_img, R.id.wallet_bai_img, R.id.wallet_mobai_img,
            R.id.wallet_haluo_img, R.id.wallet_youbai,
            R.id.id_delivery, R.id.id_iv_weather, R.id.id_iv_bus,
            R.id.id_tengxun_news, R.id.id_iv_wallet_xiecheng, R.id.id_tv_charge})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.wallet_ofo_img :
                WebActivity.actionStartWebActivity(this, Api_C.URL_OFO);
                break;
            case R.id.wallet_mobai_img :
                WebActivity.actionStartWebActivity(this, Api_C.URL_MO_BAI);
                break;
            case R.id.wallet_haluo_img :
                WebActivity.actionStartWebActivity(this, Api_C.URL_HELLO_BAI);
                break;
            case R.id.wallet_youbai :
                WebActivity.actionStartWebActivity(this, Api_C.URL_YOUBAI_BAI);
                break;
            case R.id.wallet_bai_img :
                WebActivity.actionStartWebActivity(this, Api_C.URL_XIAO_BAI);
                break;
            case R.id.id_tengxun_news :
                WebActivity.actionStartWebActivity(this, Api_C.URL_TENG_XUN);
                break;
            case R.id.id_iv_wallet_xiecheng :
                WebActivity.actionStartWebActivity(this, Api_C.URL_XIE_CHENG);
                break;
            case R.id.id_delivery :
                WebActivity.actionStartWebActivity(this, Api_C.URL_SEARCH_DIVERY);
                break;
            case R.id.id_iv_weather :
                WebActivity.actionStartWebActivity(this, Api_C.URL_WEATHER);
                break;
            case R.id.id_iv_bus :
                WebActivity.actionStartWebActivity(this, Api_C.URL_BAIDU_BUS);
                break;
            case R.id.id_tv_charge :
                showChargeDialog();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private AlertDialog mAlertDialog;
    private TextInputEditText mInputCharge = null;

    private void showChargeDialog() {
        View dialogCharge = LayoutInflater.from(this).inflate(R.layout.dialog_recharge, null, false);
        mInputCharge = (TextInputEditText) dialogCharge.findViewById(R.id.tiet_balance);

        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setView(dialogCharge)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        charge();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .setCancelable(false);
        mAlertDialog = builder.show();
    }

    private void charge() {
        Map<String, String> params = getChargeParams();
        if (params == null) return;

        mSupCharge = Api.getInstance(Api_C.BASE_URL_LIN_BASE).mApiService
                .chargeByPOST(params)
                .map(RxSchedulers.<ChargeResult>sleep(1500))
                .compose(RxSchedulers.<ChargeResult>io_main())
                .subscribe(new Action1<ChargeResult>() {
                    @Override
                    public void call(ChargeResult chargeResult) {
                        judgeChargeResult(chargeResult);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        ToastUtils.showShort(App.getAppContext(), throwable.getMessage());
                    }
                });
    }

    private void judgeChargeResult(ChargeResult chargeResult) {
        switch (chargeResult.getCode()) {
            case 25001 :
                successCharge(chargeResult);
                break;
            default:
                break;
        }
        showSnack(chargeResult.getMessage());
    }

    private void successCharge(ChargeResult chargeResult) {
        if (chargeResult == null)   return;
        saveUserNowBalance(chargeResult.getData());
    }

    private void saveUserNowBalance(ChargeResult.ChargeDataBean data) {
        if (data == null)   return;
        User userBean = LoginStatusUtil.getLoginDataByBean(this);
        if (userBean == null)   return;
        userBean.setBalance(data.getBalance());
        LoginStatusUtil.updateLoginedStatus(this, userBean);
        //
        initInfos();
    }

    @Nullable
    private Map<String, String> getChargeParams() {
        User userBean = LoginStatusUtil.getLoginDataByBean(this);
        if (userBean==null || StringUtils.isEmpty(userBean.getUserName())
                || StringUtils.isEmpty(userBean.getPassword())) return null;
        int payPrice = getPayPrice();
        if (payPrice == -1) return null;
        Map<String, String> params = new HashMap<>();
        params.put("userName", userBean.getUserName());
        params.put("password", userBean.getPassword());
        params.put("payPrice", payPrice+"");
        return params;
    }


    private int getPayPrice() {
        if (mInputCharge == null)   return -1;
        if (!isValidPayPrice(mInputCharge.getText().toString())) return -1;
        return Integer.valueOf(mInputCharge.getText().toString());
    }

    private boolean isValidPayPrice(String strPayPrice) {
        int price = 0;
        try {
            price = Integer.valueOf(strPayPrice);
        } catch (Exception e) {
            showSnack("输入的价格不合法、请重新输入");
            return false;
        }
        if (price < 0) {
            showSnack("充值金额不得低于0元");
            return false;
        }
        return true;
    }

    private void showSnack(String title) {
        ToastUtils.showSnackbar(mLlMyWellet, title, Snackbar.LENGTH_SHORT);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消登陆任务
        if (mSupCharge != null && !mSupCharge.isUnsubscribed()) {
            mSupCharge.unsubscribe();
            ToastUtils.showShort(App.getAppContext(), "取消充值");
        }
        if (mAlertDialog!=null && mAlertDialog.isShowing())   mAlertDialog.dismiss();
    }
}
